package com.pic4493.app;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.pic4493.adapter.AdpList_Reviews;
import com.pic4493.base.BaseUITopBar;
import com.pic4493.comm.PubConst;
import com.pic4493.comm.Session;
import com.pic4493.entities.DJson;
import com.pic4493.entities.EReview;
import com.pic4493.net.NetClientJ;
import com.pic4493.utils.UtiDialog;
import com.pic4493.utils.UtiUI;

public class UIPicReview extends BaseUITopBar
{

   private String mAid;

   private ListView mListView;
   private AdpList_Reviews mAdpReviews;
   private LinearLayout mMain;
   private TextView mTxtEmpty;
   private ArrayList<EReview> mList;
   private PopupWindow mPopupWindow;

   private void initView()
   {
	  mImgRight.setVisibility(View.VISIBLE);
	  mMain = (LinearLayout) findViewById(R.id.uipictalk_main);
	  mListView = (ListView) findViewById(R.id.uipictalk_list);
	  mTxtEmpty = (TextView) findViewById(R.id.uipictalk_txt_empty);
   }

   private void initEvent()
   {
	  mListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
	  {
		 @Override
		 public void onItemClick(AdapterView<?> parent, View view, int position, long id)
		 {
			if (Session.getInstance().isLogin())
			{
			   String rid = ((EReview) mAdpReviews.getItem(position)).getReviewId();
			   String name = ((EReview) mAdpReviews.getItem(position)).getNickName();
			   showReviewPopupWindow(rid, name);
			}
			else
			{
			   Intent uiIntent = new Intent();
			   uiIntent.setClass(mContext, UISignUp.class);
			   startActivityForResult(uiIntent, PubConst.ActivityJump.LOGIN);
			}

		 }
	  });
	  mImgRight.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			if (Session.getInstance().isLogin())
			{
			   showReviewPopupWindow("0", "");
			}
			else
			{
			   Intent uiIntent = new Intent();
			   uiIntent.setClass(mContext, UISignUp.class);
			   startActivityForResult(uiIntent, PubConst.ActivityJump.LOGIN);
			}
		 }
	  });
   }

   private void initData()
   {
	  executeAsyncTask("loadData");
   }

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
	  setContentView(R.layout.uipictalk);
	  super.onCreate(savedInstanceState);
	  setTitle("评论");

	  mAid = getIntent().getStringExtra(PubConst.Intent_Key.AlbumId);

	  initView();
	  initEvent();
	  initData();
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  UtiDialog.getInstance().ShowLoadingDialogNoTitleEX(mContext, "请稍候...");
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  if ("loadData".equals(taskName))
	  {
		 return NetClientJ.GetReviewsByAlbumId(mAid);
	  }
	  else if ("uploadData".equals(taskName))
	  {
		 return NetClientJ.UploadReview(params[0].toString(), params[1].toString(), params[2].toString(), params[3].toString());
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  UtiDialog.getInstance().DismissLoadingDialog();
	  try
	  {
		 if (result != null)
		 {
			DJson data = (DJson) result;
			if (!data.getHead().hasError())
			{
			   if ("loadData".equals(taskName))
			   {
				  JSONObject object = data.getBody();
				  JSONArray reviews = object.optJSONArray("review");
				  mList = getReviews(reviews);
				  mAdpReviews = new AdpList_Reviews(mContext, mList);
				  mListView.setAdapter(mAdpReviews);
				  if (mList == null || mList.size() == 0)
				  {
					 mListView.setVisibility(View.INVISIBLE);
					 mTxtEmpty.setVisibility(View.VISIBLE);
				  }
				  else
				  {
					 mListView.setVisibility(View.VISIBLE);
					 mTxtEmpty.setVisibility(View.GONE);
				  }
			   }
			   else if ("uploadData".equals(taskName))
			   {
				  UtiDialog.getInstance().ShowToastInfoShort(mContext, "评论成功");
				  mPopupWindow.dismiss();
				  initData();
			   }
			}
			else
			{
			   UtiDialog.getInstance().ShowToastInfoShort(mContext, data.getHead().getRspMsg());
			}
		 }
		 else
		 {
			UtiDialog.getInstance().ShowToastInfoShort(mContext, "网络异常请稍候再试");
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UIPicReview_onAsyncTaskEnd(taskId, taskName, params, result) " + e);
	  }
   }

   private ArrayList<EReview> getReviews(JSONArray jsonArray)
   {
	  try
	  {
		 if (jsonArray != null)
		 {
			ArrayList<EReview> list = new ArrayList<EReview>();
			EReview rev = null;
			for (int i = 0; i < jsonArray.length(); i++)
			{
			   rev = new EReview();
			   rev.setReviewId(jsonArray.optJSONObject(i).optString("rid"));
			   rev.setPicId(jsonArray.optJSONObject(i).optString("pid"));
			   rev.setContent(jsonArray.optJSONObject(i).optString("content"));
			   rev.setParentId(jsonArray.optJSONObject(i).optString("parentid"));
			   rev.setUserId(jsonArray.optJSONObject(i).optString("uid"));
			   rev.setNickName(jsonArray.optJSONObject(i).optString("nickname"));
			   rev.setDateLine(jsonArray.optJSONObject(i).optString("dateline"));
			   rev.setAvatars(jsonArray.optJSONObject(i).optString("avatars"));
			   rev.setSonList(getReviews(jsonArray.optJSONObject(i).optJSONArray("son")));
			   list.add(rev);
			}
			return list;
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UIPicReview_getReviews() " + e);
	  }
	  return null;
   }

   public void showReviewPopupWindow(final String rId, String nickName)
   {
	  try
	  {
		 LayoutInflater mInflater = LayoutInflater.from(mContext);
		 View popView = mInflater.inflate(R.layout.uipictalk_pop_reply, null);
		 Button btnOK = (Button) popView.findViewById(R.id.uipictalk_pop_btn_ok);
		 Button btnCancel = (Button) popView.findViewById(R.id.uipictalk_pop_btn_cancel);
		 TextView txt = (TextView) popView.findViewById(R.id.uipictalk_pop_txt);
		 final EditText edtContent = (EditText) popView.findViewById(R.id.uipictalk_pop_edt);

		 if (rId == null || rId.equals("") || rId.equals("0"))
		 {
			txt.setText("评论该图片");
		 }
		 else
		 {
			txt.setText("回复" + nickName);
		 }

		 btnOK.setOnClickListener(new View.OnClickListener()
		 {
			@Override
			public void onClick(View v)
			{
			   if (edtContent.getText().toString().trim().equals(""))
			   {
				  UtiDialog.getInstance().ShowToastInfoShort(mContext, "评论内容不能为空");
			   }
			   else
			   {
				  executeAsyncTask("uploadData", new Object[] { mAid, edtContent.getText().toString().trim(), rId, Session.getInstance().getUser().getNickName() });
			   }
			}
		 });
		 btnCancel.setOnClickListener(new View.OnClickListener()
		 {
			@Override
			public void onClick(View v)
			{
			   mPopupWindow.dismiss();
			}
		 });

		 mPopupWindow = new PopupWindow(popView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		 mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		 mPopupWindow.setAnimationStyle(R.style.Anim_Popup);
		 mPopupWindow.setFocusable(true);
		 mPopupWindow.setOutsideTouchable(true);
		 mPopupWindow.showAtLocation(mMain, Gravity.BOTTOM | Gravity.CENTER, 0, UtiUI.getInstance().getScreenHeight() / 2);
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UtiMenu_ShowReviewPopupWindow(conte1xt) " + e);
	  }
   }
}
